/* 用户管理 */
import Vue from "vue";
import {
    getToken,
    setToken,
    removeToken,
    setUserInfo,
    getUserInfo
} from "@/utils/auth";
import { resetRouter } from "@/router";
import Store from "../index.js";

const state = {
    token: getToken(),
    userInfo: {}, // 用户登录信息
    userId: "", // 用户id
    name: "", // 用户名
    rolesTree: [], // 用户权限树
    customTree: [] // 自定义路由
};

const getters = {
    GET_USERINFO: state => state.userInfo
};

const mutations = {
    // 设置用户登录信息
    SET_USERINFO: (state, userInfo) => { state.userInfo = userInfo; },

    // 设置用户名称
    SET_NAME: (state, name) => { state.name = name; },

    // 设置用户权限
    SET_ROLESTREE: (state, rolesTree) => { state.rolesTree = rolesTree; },

    /* 清空用户权限与用户权限树 */
    CLEAN_ROLES: ( state ) => {
        state.roles = [];
        state.rolesTree = [];
    },

    /* 用于存储任意键值对: { key: 键名, value: 值 } */
    SET_COMMON: (state, obj) => {
        state[obj.key] = obj.value;
    }
};

const actions = {
    /* 用户登录触发, 带进登录成功的返回参数 */
    async login ({ commit }, loginInfo) {
        commit("SET_COMMON", { key: "token", value: loginInfo.token });
        commit("SET_COMMON", { key: "userId", value: loginInfo.userId });
        commit("SET_COMMON", { key: "userInfo", value: loginInfo });
        setToken(loginInfo.token); // 缓存token
        setUserInfo(JSON.stringify(loginInfo)); // 缓存用户信息
    },

    // 获取本地缓存中的用户信息，并设置到vuex中
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            const userInfo = eval( "(" + getUserInfo() + ")" );
            const data = userInfo.accountInfo || {};
            commit("SET_COMMON", { key: "rolesTree", value: eval(userInfo.rolePermission) }); // 设置用户权限树
            commit("SET_COMMON", { key: "userInfo", value: userInfo });
            resolve(data);
        });
    },

    /* 用户登出触发 */
    logout ({ commit, state, dispatch }) {
        const userInfo = {
            access_token: "",
            userId: "",
            username: "",
            hospitalCode: "",
            hospital_name: "",
            role_code: "",
            role_name: ""
        };
        commit("SET_COMMON", { key: "userInfo", value: "" }); // 清除token
        commit("SET_COMMON", { key: "rolesTree", value: [] }); // 清除权限树
        removeToken(); // 清除缓存token
        setUserInfo(userInfo); // 清除缓存用户信息
        resetRouter();
    }
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
};